package com.cq.hd.common.response;

import com.cq.hd.common.enums.ResponseEnums;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;

/**
 * @description: 前后端交互类
 * @author: mYunYu
 * @date: 2021/7/7 15:47
 * @version: v1.0
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {

    /**
     * 状态码
     */
    private int code;

    /**
     * 返回的消息
     */
    private String message;

    /**
     * 结果集
     */
    private T data;

    public Result() {
        this.code = ResponseEnums.SUCCESS.getCode();
        this.message = ResponseEnums.SUCCESS.getMessage();
    }

    public Result(int code, String message) {
        this.code = code;
        this.message = message == null ? "服务器繁忙" : message;
    }

    public Result(int code, String message, T result) {
        this.code = code;
        this.message = message;
        this.data = result;
    }


    /**
     * 验证其它服务是否调用成功
     */
    public Result<T> isSuccess() {
        if (this.code != ResponseEnums.SUCCESS.getCode()) {
            Throw.isRpcCallException(code, message);
        }
        return this;
    }

    /**
     * 验证其它服务是否调用失败
     */
    public Result<T> notError() {
        if (this.code == ResponseEnums.ERROR.getCode()) {
            Throw.isRpcCallException(code, message);
        }
        return this;
    }

    /**
     * 解包
     */
    public T unpack() {
        return isSuccess().data;
    }

}
